<template>
    <div>
        <!-- 面包屑导航 -->
         <el-breadcrumb separator-class="el-icon-arrow-right">
           <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
           <el-breadcrumb-item>商品管理</el-breadcrumb-item>
           <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 页头警告区域 -->
            <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning"
            show-icon :closable='false'>
            </el-alert>
            <!-- 商品分类区域 -->
            <p>
               选择商品分类:
                 <el-cascader
                    v-model="categoryKey"
                    :options="categoryList"
                    :props="addCateObj"
                    @change="handleChange">
                </el-cascader>
            </p>
            <!-- 商品详情区域 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <!-- 添加动态参数面板 -->
                <el-tab-pane label="动态参数" name="many"></el-tab-pane>
                <el-tab-pane label="静态属性" name="only"></el-tab-pane>

                 <el-button type="success" size='small' @click='addParams' :disabled="flag">{{activeName==='many'?'添加动态参数':'添加静态属性'}}</el-button>
                      <el-table
                            stripe
                            border
                            :data='ParamsList'
                            style="width: 100%">
                             <el-table-column type="expand">
                            <template slot-scope="props">
                              <el-form label-position="left" inline class="demo-table-expand">
                                <el-form-item>
                                <span><el-tag
                                v-for="(tag, index) in props.row.attr_vals"
                                :key="index"
                                @close="handleClose(tag, props.row)"
                                closable
                                type="success">
                                {{tag}}
                                </el-tag>
                                 <el-input
                                    class="input-new-tag"
                                    v-if="props.row.inputVisible"
                                    v-model="props.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(props.row)"
                                    @blur="handleInputConfirm(props.row)"
                                    >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(props.row)">+ New Tag</el-button>
                                </span>
                                </el-form-item>
                              </el-form>
                            </template>
                            </el-table-column>
                            <el-table-column
                              type='index'
                              label="#"
                              >
                            </el-table-column>
                            <el-table-column
                              prop="attr_name"
                              label="参数名称"
                              >
                            </el-table-column>
                            <el-table-column
                              label="操作">
                             <template slot-scope="scope">
                              <el-button type="primary" size='small' icon="el-icon-edit" @click='showEditForm(scope.row)'>编辑</el-button>
                              <el-button type="danger"  size='small' icon="el-icon-delete" @click='toDeleteParams(scope.row)'>删除</el-button>
                             </template>
                            </el-table-column>
                    </el-table>
                <!-- 添加静态属性面板 -->
            </el-tabs>
        </el-card>
     <!-- 添加参数对话框 -->
        <el-dialog
            :title="activeName==='only'?'添加静态属性':'添加动态参数'"
            :visible.sync="addParamsVisible" @close='resetForm("addParamsRef")'
            width="30%"
            >
            <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsRef" label-width="100px" class="demo-ruleForm">
            <el-form-item :label="activeName==='only'?'静态属性':'动态参数'" prop="attr_name">
                <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addParamsVisible = false">取 消</el-button>
              <el-button type="primary" @click='toAddParams'>确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑参数对话框 -->
         <el-dialog
            :title="activeName==='only'?'编辑静态属性':'编辑动态参数'"
            :visible.sync="editParamsVisible"  @close='resetForm("editParamsRef")'
            width="30%"
            >
            <el-form :model="editParamsForm" :rules="addParamsRules" ref="editParamsRef" label-width="100px" class="demo-ruleForm">
            <el-form-item :label="activeName==='only'?'静态属性':'动态参数'" prop="attr_name">
                <el-input v-model="editParamsForm.attr_name"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editParamsVisible = false">取 消</el-button>
              <el-button type="primary" @click='toEditParams'>确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
    // 商品分类
      categoryList: [],
      //   分类选项的相关配置对象
      addCateObj: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      //   分类数据绑定的数据
      categoryKey: [],
      activeName: 'many',
      //   按钮禁用判断
      flag: true,
      //   分类id
      ParamsId: '',
      //   动态参数输入值
      addParamsForm: {
        attr_name: ''
      },
      //   编辑表单
      editParamsForm: {},
      //   分类动态参数数据
      ParamsList: [],
      //   添加参数显示框
      addParamsVisible: false,
      //   编辑参数显示框
      editParamsVisible: false,
      //   输入框显示
      inputVisible: false,
      //   标签数据数组
      tagArry: '',
      //   输入框
      inputValue: '',
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    //   获取商品分类数据
    this.getCategories()
  },
  methods: {
    //   获取商品分类
    async getCategories () {
      const data = await this.$http.get('categories', { type: 3 })
      if (data.meta.status !== 200) return this.$message.error('获取分类数据失败')
      this.categoryList = data.data
    },
    // 改变选项触发的事件
    handleChange () {
    // 获取选中的选项
      if (this.categoryKey.length !== 3) {
        // 如果选中的不是三级分类就将选中的数据清空
        this.categoryKey = []
        // 将数据清空并隐藏
        this.ParamsList = []
        this.getCategories()
        return false
      } else {
        // 按钮不禁用
        this.ParamsId = this.categoryKey[this.categoryKey.length - 1]
        this.flag = false
        // 获取商品参数分类
        this.getParamsData()
      }
    },
    // 获取商品参数列表数据
    async getParamsData () {
      const data = await this.$http.get('categories/' + this.ParamsId + '/attributes', {
        params: { sel: this.activeName }
      })
      if (data.meta.status !== 200) return this.$message.error('获取参数失败')
      console.log(data.data)
      const lists = data.data
      lists.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(lists)
      this.ParamsList = lists
    },
    // 切换tab触发事件
    handleClick (val) {
    // 将选中的tab值传给activeName
      this.activeName = val.name
      //   重新获取数据
      this.getParamsData()
    },
    // 添加参数分类对话框
    addParams () {
      this.addParamsVisible = true
    },
    // 显示编辑对话框
    showEditForm (val) {
      this.editParamsVisible = true
      this.editParamsForm = val
    },
    // 重置对话框
    resetForm (val) {
      this.$refs[val].resetFields()
    },
    // 编辑参数
    toEditParams () {
      this.$refs.editParamsRef.validate(async (valid) => {
        if (!valid) {
          return this.$Message.error('信息输入错误，请重新输入正确格式')
        } else {
        // 发送添加用户信息请求
          const data = await this.$http.put('categories/' + this.editParamsForm.cat_id + '/attributes/' + this.editParamsForm.attr_id, {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.tagArry
          })
          if (data.meta.status === 200) {
            this.$message.success('修改参数成功')
            // 获取分类动态参数数据
            this.getParamsData()
            this.editParamsVisible = false
          } else {
            this.$Message.error('修改参数失败')
          }
        }
      })
    },
    // 添加参数
    toAddParams () {
      this.$refs.addParamsRef.validate(async (valid) => {
        if (!valid) {
          return this.$Message.error('信息输入错误，请重新输入正确格式')
        } else {
        // 发送添加用户信息请求
          const data = await this.$http.post('categories/' + this.ParamsId + '/attributes', {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.tagArry
          })
          if (data.meta.status === 201) {
            this.$message.success('创建动态参数成功')
            // 获取分类动态参数数据
            this.getParamsData()
            this.addParamsVisible = false
          } else {
            this.$Message.error('修改用户失败')
          }
        }
      })
    },
    // 删除参数
    toDeleteParams (val) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$http.delete('categories/' + val.cat_id + '/attributes/' + val.attr_id)
        this.getParamsData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除数据标签
    async handleClose (tag, val) {
      val.attr_vals.splice(val.attr_vals.indexOf(tag), 1)
      //   重新去修改数据
      await this.$http.put('categories/' + val.cat_id + '/attributes/' + val.attr_id, {
        attr_name: val.attr_name,
        attr_sel: val.attr_sel,
        attr_vals: val.attr_vals.join(' ')
      })
    },
    // 输入标签内容事件
    async handleInputConfirm (val) {
      var inputvalue = val.inputValue
      if (inputvalue.trim().length > 0) {
        val.attr_vals.push(inputvalue)
      } else {
        val.inputValue = ''
        val.inputVisible = false
        return false
      }
      await this.$http.put('categories/' + val.cat_id + '/attributes/' + val.attr_id, {
        attr_name: val.attr_name,
        attr_sel: val.attr_sel,
        attr_vals: val.attr_vals.join(' ')
      })
      val.inputVisible = false
      val.inputValue = ''
    },
    // 展现标签事件
    showInput (row) {
      row.inputVisible = true
      //   当页面重新渲染后发生的回调函数--
      this.$nextTick(_ => {
        //   必须放在回调函数内，否则不执行--获取不到元素
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }

  }
}
</script>

<style lang="less" scoped>
.el-input {
    width: 80%;
}
.el-tag {
    margin-right: 20px;
}
</style>
